<template>
  <el-form :model="form" label-width="120px" class="login">
    <h1>用户登录</h1>
    <el-form-item label="用户名">
      <el-input v-model="form.username" />
    </el-form-item>
    <el-form-item label="密码">
      <el-input v-model="form.password" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">登录</el-button>
      <el-button @click="onReset">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive } from 'vue'
// do not use same name with ref
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
const store = useStore()
const router = useRouter()
const form = reactive({
  username: '',
  password: ''
})

const onSubmit = () => {
  store.dispatch('login', form).then((resp) => {
    ElMessage({ type: 'success', message: resp.data.message })
    router.push({ name: 'home' })
  }).catch((message) => {
    ElMessage({ type: 'error', message })
  })
}

const onReset = () => {
  form.password = ''
  form.username = ''
}
</script>

<style>
h1 {
  margin:  10px 0;
  text-align: center;
}
.login {
  position: fixed;
  top: 40%;
  transform: translateY(-50%);
  right: 100px;
  width: 500px;
  padding: 10px;
}
</style>